
#include "./gro.h"

int mds_gro_save(const char          *filename, 
				 const char          *comment,
				 const mds_vector_set position,
				 const mds_vector_set velocity,
				 const size_t         num,
				 const mds_vector    *box,
				 int                  append)
{
	FILE *fp      = NULL;
	char  mode[4] = { (char)(append ? 'a' : 'w'), 'b', '\0', '\0' };
	
	assert(filename);
	assert(position);
	assert(num>0);
	assert(box);
	
	if( NULL == ( fp = fopen( filename, mode ) ) )
	{
		return -1;
	}
	else 
	{
		const char residue[] = "Ar";
		const char atom_id[] = "Ar";
		register unsigned i;
		
		if( comment ) fprintf( fp, "%s", comment );
		fprintf( fp, "\n" );
		fprintf( fp, "%u\n", (unsigned) num );
		
		for( i=0; i < num; ++i )
		{
			const int         index = i % 100000;
			const mds_vector *r     = &position[i];
			Real vx=0,vy=0,vz=0;
			if( velocity )
			{
				const mds_vector *v     = &velocity[i];
				vx = v->x;
				vy = v->y;
				vz = v->z;
			}
			fprintf( fp, "%5d%5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f\n", index, residue, atom_id, 1,  r->x, r->y, r->z, vx, vy, vz);			
		}
		fprintf( fp, "%8.3f %8.3f %8.3f\n", box->x, box->y, box->z );
		fclose( fp );
		return 0;
	}
	
}
